#include <stdlib.h>
#include <pthread.h>
#include <iostream>

using std::cout;
using std::endl;

//单例模式的自动释放第四种形式：pthread_once +atexit
///pthread_once与平台相关
class Singleton
{
public:
    static Singleton *getInstance()
    {
        pthread_once(&_once, init);
        return _pInstance;
    }

    static void init()
    {
        _pInstance = new Singleton();
        atexit(destroy);
    }

    static void destroy()
    {
        if(_pInstance)
        {
            delete _pInstance;
            _pInstance = nullptr;
        }
    }

private:
    Singleton()
    {
        cout <<"Singleton()" << endl;
    }

    ~Singleton()
    {
        cout <<"~Singleton()" << endl;
    }

private:
    static Singleton *_pInstance;
    static pthread_once_t _once;
};

//饱汉(懒汉)模式
Singleton *Singleton::_pInstance = nullptr;

//饿汉模式
/* Singleton *Singleton::_pInstance = Singleton::getInstance(); */
pthread_once_t Singleton::_once = PTHREAD_ONCE_INIT;

void test()
{
    Singleton::getInstance();
}

int main(int argc, char *argv[])
{
    test();
    return 0;
}

